<?php

class MemberPurchaseAccountBalance extends DataExtension {
	private static $casting = array(
        'PurchaseAccountBalance' => 'Currency'
    );
	
    function augmentWrite(&$manipulation) {
        $tables = array_keys($manipulation);
        $version_table = array();
        foreach($tables as $table) {
            $baseDataClass = ClassInfo::baseDataClass($table);

            $isRootClass = ($table == $baseDataClass);
            if($isRootClass && $manipulation[$table]['command'] == 'insert' && isset($manipulation[$table]['id']) && $manipulation[$table]['id']) {
                DB::query("INSERT INTO PurchaseAccountBalance (MemberID) VALUES (".$manipulation[$table]['id'].")");
            }
        }
    }
	
	function requireDefaultRecords() {
		$result = DB::query("SELECT * FROM Member WHERE ID NOT IN (SELECT MemberID FROM PurchaseAccountBalance)");
		foreach($result as $item){
			DB::query("INSERT INTO PurchaseAccountBalance (MemberID) VALUES (".$item['ID'].")");
		}
	}
	
	function getPurchaseAccountBalance(){
		return Account::get('PurchaseAccount', $this->owner->ID)->getBalance();
	}
}
?>